package com.hue.concurrent.day07;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * 自己封装updateAndGet方法
 */
public class Demo02 {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);
        System.out.println(updateAndGet(atomicInteger, x -> x * 2));
//        System.out.println(atomicInteger.get());
    }

    public static int updateAndGet(AtomicInteger integer, IntUnaryOperator operator) {
        int pre;
        int next;
        do {
            pre = integer.get();
            next = operator.applyAsInt(pre);
        } while (!integer.compareAndSet(pre, next));
        return next;
    }
}
